import axios from "axios";
import {showNotify} from 'vant';
import {StorageUtil} from './storage';
import {apiDev, apiProd} from '@/config/url';
import {URL} from '@/config/url';


// 创建axios实例
const service = axios.create({
    baseURL: apiDev, // 基础URL从环境变量读取
    timeout: 10000, // 请求超时时间
});

// 请求拦截器
service.interceptors.request.use(
    config => {
        // 获取token和卡密
        const token = StorageUtil.getToken();

        // 添加token和卡密到请求头
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`;
        }

        return config;
    },
    error => {
        // 对请求错误做些什么
        console.error('Request Error:', error);
        return Promise.reject(error);
    }
);

const projectId = StorageUtil.getProjectId();

// 响应拦截器
service.interceptors.response.use(
    response => {
        // 根据返回的code判断响应状态
        const res = response.data;

        if (res.code === 401) {
            // 清除存储并跳转到登录页
            StorageUtil.clear();
            // 这里可以添加跳转到登录页的逻辑
            window.location.href = URL + `?id=${projectId}` ;
        } else if (res.code !== 200) {
            // 处理错误响应
            showNotify({type: 'warning', message: res.messages || '请求发生错误'});
            // 这里可以添加跳转到登录页的逻辑
            window.location.href = URL + `?id=${projectId}`;

            return Promise.reject(res.message);
        }

        return res?.data || {};
    },
    error => {
        // 处理网络错误
        console.error('interceptors', error);
        window.location.href = URL + `?id=${projectId}`;
        showNotify({type: 'danger', message: error});
        return Promise.reject(error);
    }
);

// GET请求
export const get = (url, params) => {
    return service.get(url, {params});
};

// POST请求
export const post = (url, data) => {
    return service.post(url, data);
};

// PUT请求
export const put = (url, data) => {
    return service.put(url, data);
};

// DELETE请求
export const del = (url, params) => {
    return service.delete(url, {params});
};

// 文件上传请求
export const upload = (url, file) => {
    const formData = new FormData();
    formData.append('file', file);
    return service.post(url, formData, {
        headers: {'Content-Type': 'multipart/form-data'}
    });
};

export default service;